package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.CreativeAchievement;
import com.gxuwz.stats.service.CreativeAchievementService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/creativeAchievement")
public class CreativeAchievementController {

    @Autowired
    private CreativeAchievementService creativeService;

    @Autowired
    private UserService userService;

    /**
     * 分页查询创作成果数据
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getCreativeList(
            @RequestParam(required = false) String nameKeyword,
            @RequestParam(required = false) String categoryKeyword,
            @RequestParam(required = false) String levelKeyword,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            IPage<CreativeAchievement> page = new Page<>(currentPage, pageSize);
            QueryWrapper<CreativeAchievement> queryWrapper = new QueryWrapper<>();

            // 构建查询条件
            if (StringUtils.hasText(nameKeyword)) {
                queryWrapper.like("creative_achievement_name", nameKeyword);
            }
            if (StringUtils.hasText(categoryKeyword)) {
                queryWrapper.eq("creative_category", categoryKeyword);
            }
            if (StringUtils.hasText(levelKeyword)) {
                queryWrapper.eq("creative_level", levelKeyword);
            }

            IPage<CreativeAchievement> resultPage = creativeService.getCreativeAchievementList(page, queryWrapper);

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增创作成果数据
     */
    @PostMapping("/add")
    public ResponseEntity<?> saveCreative(@RequestBody CreativeAchievement creativeAchievement) {
        try {
            // 1. 验证username是否存在
            String username = creativeAchievement.getUsername();
            if (!StringUtils.hasText(username)) {
                return ResponseEntity.badRequest().body("用户名不能为空");
            }

            // 2. 根据username查询user_id
            Integer userId = userService.getUserIdByUsername(username);
            if (userId == null) {
                return ResponseEntity.badRequest().body("用户不存在");
            }

            // 3. 设置user_id并保存
            creativeAchievement.setUserId(userId.intValue());
            boolean isSaved = creativeService.save(creativeAchievement);

            Map<String, Object> response = new HashMap<>();
            if (isSaved) {
                response.put("code", HttpStatus.CREATED.value());
                response.put("message", "新增成功");
                return ResponseEntity.status(HttpStatus.CREATED).body(response);
            } else {
                response.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.put("message", "新增失败");
                return ResponseEntity.internalServerError().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    /**
     * 批量删除创作成果数据
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteCreative(@RequestBody List<Long> ids) {
        try {
            boolean isRemoved = creativeService.removeByIds(ids);
            Map<String, Object> response = new HashMap<>();
            if (isRemoved) {
                response.put("code", HttpStatus.NO_CONTENT.value());
                response.put("message", "删除成功");
                return ResponseEntity.noContent().build();
            } else {
                response.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.put("message", "删除失败");
                return ResponseEntity.internalServerError().body(response);
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
            errorResponse.put("message", "服务器错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    /**
     * 修改创作成果数据（修复静态方法调用和添加校验逻辑）
     */
    @PutMapping("/update/{id}")
    public ResponseEntity<Map<String, Object>> updateCreative(
            @PathVariable("id") Long id,
            @RequestBody CreativeAchievement creativeAchievement) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 1. 用户名校验
            String username = creativeAchievement.getUsername();
            if (!StringUtils.hasText(username)) {
                response.put("code", HttpStatus.BAD_REQUEST.value());
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 2. 用户存在性校验
            Integer userId = userService.getUserIdByUsername(username);
            if (userId == null) {
                response.put("code", HttpStatus.BAD_REQUEST.value());
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }

            // 3. 设置ID和用户ID
            creativeAchievement.setCreativeId(id);
            creativeAchievement.setUserId(userId);

            // 4. 修复：正确调用实例方法
            boolean isUpdated = creativeService.updateById(creativeAchievement);

            // 5. 返回响应
            response.put("code", isUpdated ? HttpStatus.OK.value() : HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.put("message", isUpdated ? "修改成功" : "修改失败");
            return isUpdated ? ResponseEntity.ok(response) : ResponseEntity.internalServerError().body(response);

        } catch (Exception e) {
            response.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.put("message", "服务器错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}